package com.yunshang.shoppingmall.shopping.productApi.controller;

import com.yunshang.shoppingmall.common.QRCodeUtil;
import com.yunshang.shoppingmall.common.UploadImgs;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.entity.MergeImage;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinChat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 二维码生成类
 */
@Controller
@RequestMapping("/wap")
public class ErWeiMaController {

    @Autowired
    PannerService pannerService;
    @Autowired
    ProductGuiGeService productGuiGeService;
    @Autowired
    ProductService productService;

    @Autowired
    ProductPriceService productPriceService;
    @Autowired
    EwmService ewmService;

    @Autowired
    ProductAllViewService productAllViewService;

    @Autowired
    ShareImagesConfigService shareImagesConfigService;

    @ResponseBody
    @RequestMapping("/getEnCode")
    public Map<String, Object> getEnCode(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        //商品Id
        String productId = request.getParameter("productId");
        System.out.println("productId:" + productId);
        int productIds = 154;
        String text = null;
        String Imgurl = null;
        String productName = null;
        int guigeId = 0;
        double proPrices = 0.00;
        BigDecimal proPrice = null;
        List<ProductGuiGe> productGuiGeList = null;
        //合成图片的参数
        ShareImagesConfig shareImagesConfig=shareImagesConfigService.selectByPrimaryKey(1);
        //登录用户id
        int userNoId=0;
        UserNo userNo =(UserNo) request.getSession().getAttribute("userNo");
        if(userNo!=null){
            userNoId=userNo.getId();
        }else{
            map.put("loginInfo","unlogin");
            return  map;
        }

        if (productId != null && productId != "") {
            productIds = Integer.parseInt(productId);
            text = WinChat.severUrl +"/wap/Share?lx=3&productId=" + productIds + "&uid="+userNoId;
            Product product = productService.selectByPrimaryKey(productIds);
            if (product != null) {
                productName = product.getProductName();
            }
            productGuiGeList = productGuiGeService.selectGuigeListByProductId(productIds);
            if (productGuiGeList != null) {
                Imgurl = productGuiGeList.get(0).getImgurl();
                guigeId = productGuiGeList.get(0).getGuigeId();
            }
            ProductPrice productPrice = productPriceService.selectProductPriceByGuigeId(guigeId);
            if (productPrice != null) {
                proPrice = productPrice.getProPrice();
            }
        }else{
            return map;
        }



        //logo图片
        int pannerActiveSign = 2;
        List<Panner> pannersList = pannerService.selectPanners(pannerActiveSign);
        String logoImgURL = pannersList.get(0).getPannerUrl();

        //获取路径
        try {

//            //服务器
            File path=new File("/usr/local/mall_uploads");
            if(!path.exists()){
                path = new File("");
            }

            //本地
//            File path = new File("E:/images/uploads/");
//            if (!path.exists()) {
//                path.mkdirs();
//            }



            String logoUrl = path + logoImgURL;
            String erWMImgUrl=path+"/";
            System.out.println("---erWMImgUrl--------->"+erWMImgUrl);
            //生成二维码
            String URl = QRCodeUtil.encode(text, logoUrl, erWMImgUrl, true);//二维码路径
            System.out.println("URI:" + URl);

            //二维码背景图图片
            pannerActiveSign = 100;
            List<Panner> pannersList1 = pannerService.selectPanners(pannerActiveSign);
            String imgURL = pannersList1.get(0).getPannerUrl();
//            String bgImg = path + imgURL;//背景图路径
            String bgImg = path+imgURL;//背景图路径
            System.out.println("背景图路径：" + bgImg);

            FileInputStream fis = new FileInputStream(bgImg);
            String uuId = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
            String outImg=path+"/"+uuId+".png";
//            String outImg = uploadPath + "/" + uuId + ".png";
            System.out.println("outImg:" + outImg);

            FileOutputStream out = new FileOutputStream(outImg);
            int n = 0;
            byte[] buff = new byte[1024];
            while ((n = fis.read(buff)) != -1) {
                out.write(buff, 0, n);
            }
            out.close();
            fis.close();

            //合成图片--背景图片和二维码合成
            MergeImage.mergeImage(outImg, URl, shareImagesConfig.getEwmImgX().toString(), shareImagesConfig.getEwmImgY().toString());

            //商品图片路径
            String guigeImgUrl = productGuiGeList.get(0).getImgurl();
            System.out.println("guigeimgurl----------------->"+guigeImgUrl);

//            String str = "E:/images/uploads" + guigeImgUrl;//本地

            String str="/usr/local/mall_uploads/"+guigeImgUrl;//服务器
            System.out.println("===========str========>" + str);

            MergeImage.mergeImage(outImg, str, shareImagesConfig.getProX().toString(), shareImagesConfig.getProY().toString());//商品图和带有二维码的图片合成

            //添加文字36
            Font font = new Font(shareImagesConfig.getShareFont(), Font.PLAIN, shareImagesConfig.getFontSize()); //水印字体
            String srcImgPath = outImg; //源图片地址
            String tarImgPath = outImg;//待存储的地址
            String waterMarkContent = productName;  //水印内容

            //在图片合成的图片上添加商品名称
            Color color = new Color(0, 0, 0, 200);//水印图片色彩以及透明度
//            srcImgPath = addWaterMark(srcImgPath, tarImgPath, waterMarkContent, color, font, shareImagesConfig.getProNameX(), shareImagesConfig.getProNameY());
            String imagesPath = addWaterMark(srcImgPath, tarImgPath, waterMarkContent, color, font, shareImagesConfig.getProNameX(), shareImagesConfig.getProNameY());


            //在合成的图片上添加价格
//            String waterMarkContent1 = "￥" + proPrice.toString(); //水印内容
//            Font font1 = new Font(shareImagesConfig.getShareFont(), Font.PLAIN, shareImagesConfig.getFontSize());
//            Color color1 = new Color(255, 0, 0, 200);//水印图片色彩以及透明度
//            String imagesPath = addWaterMark(srcImgPath, tarImgPath, waterMarkContent1, color1, font1, shareImagesConfig.getAddFontX(), shareImagesConfig.getAddFontY());

            //图片合成完获取图片的url,截取图片的相对路径

            String imagesURL = null;

//            imagesURL = imagesPath.split("/uploads")[1];//本地
                imagesURL=imagesPath.split("/mall_uploads")[1];

            map.put("ewmURL", imagesURL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public String addWaterMark(String srcImgPath, String tarImgPath, String waterMarkContent, Color markContentColor, Font font, int x, int y) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);//得到文件
            Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高


            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setColor(markContentColor); //根据图片的背景设置水印颜色
            g.setFont(font); //设置字体

            //设置水印的坐标
//            int x = srcImgWidth - 2 * getWatermarkLength(waterMarkContent, g);
//            int y = srcImgHeight - 2 * getWatermarkLength(waterMarkContent, g);
            g.drawString(waterMarkContent, x, y);  //画出水印
            g.dispose();
            String uuId = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
            String filename = "erwm"+uuId + ".png";
//            String localImgPath = "E:/images/uploads/ewmimages";//本地
            String localImgPath="/usr/local/mall_uploads/";
            File file = new File(localImgPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            tarImgPath = localImgPath + filename;
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            ImageIO.write(bufImg, "png", new File(tarImgPath));
            System.out.println("添加水印完成");
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tarImgPath;
    }

    public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }


}
